﻿using HospitalSelfServiceMachine.Adorners;
using HospitalSelfServiceMachine.Controls;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

namespace HospitalSelfServiceMachine.Utils
{
    public static class WindowsHelpers
    {
        public static bool? MaskShowDialog(this Window outputWindow)
        {
            CreateMask(outputWindow);
            var parent = GetDefaultWindow();
            outputWindow.Owner = parent;
            return outputWindow.ShowDialog();
        }

        public static void CreateMask(this Window outputWindow)
        {
            Visual parent = GetDefaultWindow();
            var _layer = GetAdornerLayer(parent);
            if (_layer == null) return;

            var _adornerContainer = new MaskAdorner(_layer)
            {
                Child = new MaskControl(parent)
            };
      
            _layer.Add(_adornerContainer);
            if (outputWindow != null)
            {
                outputWindow.Closed += delegate
                {
                    if (parent != null)
                        _layer.Remove(_adornerContainer);
                };
            }
        }

        public static Window GetDefaultWindow()
        {
            Window window = null;
            if (Application.Current != null && Application.Current.Windows.Count > 0)
            {
                window = Application.Current.Windows.OfType<Window>().FirstOrDefault(o => o.IsActive);
                if (window == null)
                    window = Enumerable.FirstOrDefault(Application.Current.Windows.OfType<Window>());
            }
            return window;
        }

        public static AdornerLayer GetAdornerLayer(Visual visual)
        {
            if (visual == null) return null;
            if (visual is AdornerDecorator decorator)
                return decorator.AdornerLayer;
            if (visual is ScrollContentPresenter presenter)
                return presenter.AdornerLayer;
            if (visual is Window window)
            {
                var visualContent = window.Content as Visual;
                return AdornerLayer.GetAdornerLayer(visualContent ?? visual);
            }
            return AdornerLayer.GetAdornerLayer(visual);
        }
    }
}
